const {
	Controller
} = require('uni-cloud-router');
/**
 * 此为仿j照绑定电话号码制作的绑定邮箱模块，意在集合设置邮箱的功能
 */
module.exports = class BindEmailController extends Controller {
	constructor(ctx) {
		super(ctx)
	}
	/**
	 * 绑定邮箱
	 * __此处解绑邮箱无效，绑定新邮箱即可覆盖旧邮箱
	 */
	async bindEmail() {
		let {
			email,
			uid,
		} = this.ctx.data; //获取请求参数 __wjf
		let re = await this.setEmailVerifyCode(email, 'bind', 3600); //再设置一个新的验证码，并保存到数据库，以满足API的参数要求
		return await this.ctx.uniID.bindEmail({
			email,
			uid,
			code: re.code
		}).then((res) => {
			console.log('绑定邮箱成功', res);
			return {
				errCode:0,
				code:0
			}
		}).catch(err => {
			console.log('绑定失败');
			return err
		})

	}
	/**
	 * 解绑邮箱 __此处解绑邮箱无效
	 */
	async unbindEmail() {
		let {
			email,
			uid,
		} = this.ctx.data; //获取请求参数 __wjf
		let re = await this.setEmailVerifyCode(email, 'unbind', 3600); //再设置一个新的验证码，并保存到数据库，以满足API的参数要求
		let res = await this.ctx.uniID.unbindEmail({
			email,
			uid,
			code: re.code
		})


		return {
			errCode: 0,
			res
		}
	}
	//设置验证码__wjf
	async setEmailVerifyCode(email, type, expiresIn) {
		let code = this.getRandomCode(); //取得验证码
		let params = {
			email,
			code,
			type,
			expiresIn: expiresIn,
		}
		await this.ctx.uniID.setVerifyCode(params);
		console.log('设置验证码email', params)
		return params;
	}
	/**
	 * 获取随机验证码
	 */
	getRandomCode() {
		return (Math.random() + "").substr(2, 6);
	}
}
